<?php

class Signup_model extends Model
{

	function __construct(){
		parent::__construct();
	}

	public function xhrInsert()
	{
		$error 		= array();

		$Birth_Date = $_POST['day'].'-'.$_POST['month'].'-'.$_POST['year'];

		$Validate_birthday = $this->f->validateDate($Birth_Date,'d-m-Y');

		$FirstName 	= $this->f->validate_input_text('/^[\f\t\r\n\w\'.-]\p{L}{2,20}$/i',$_POST['FirstName']);
		$LastName  	= $this->f->validate_input_text('/^[\w\'.-]{2,20}$/i',$_POST['LastName']);
		$Email  	= $this->f->validate_Email($_POST['Email']);
		$Re_Email  	= $this->f->validate_Email($_POST['Re_Email']);
		$Password  	= $this->f->validate_input_text('/^[\w\'.-]{6,20}$/i',$_POST['Password']);
		$count = 0;

		if($FirstName 	== false) $error[] = 'FirstName';
		if($LastName 	== false) $error[] = 'LastName';
		if($Password 	== false) $error[] = 'Password';
		if($Email 		== false) $error[] = 'Email';
		if($Re_Email 	== false) $error[] = 'Re_Email';

		if($Validate_birthday) {
			$Birth_Date = date('d-m-Y',strtotime($Birth_Date));
		}
		else $error[] = 'Birthday';

		if($Email){
			$q = $this->db->prepare("SELECT User_Id FROM users WHERE Email = :email ");
			$q->execute(array(
				':email' 	=> 	$Email,
			));

			$count = $q->rowCount();

			if($count != 0){
				$error[] = 'Email';
			}else {
				if($Email != $Re_Email) $error[] = 'Re_Email';
			}
		}
		if(empty($error))
		{
			// MD5 is not even remotely secure
			$pass = Hash::create('md5',$_POST['Password'],HASH_PASSWORD_KEY);
			
			$q = $this->db->insert('place',array(
				'FirstName' 	=> 	$FirstName,
				'LastName'		=>	$LastName,
				'Email' 		=> 	$Email,
				'Password'		=>	$pass,
				'Gender' 		=> 	$_POST['Gender'],
				'Birth_Date'	=>	$Birth_Date
			));
			// return array
			//$data = $q->fetchAll();
			$error[] =  $q;
			if($value){
				$error[] =  true;
				Session::init();
				Session::set('loggerIn',true);
				$this->f->send_email($Email,'Admin WWG','Minh Le','kick hoat tai khoan WWG','Kick hoat ');
			}
		}else {
			echo json_encode($error);
		}
	}

	public function xhrCheckEmail()
	{
		$q = $this->db->prepare("SELECT User_Id FROM users WHERE Email = :email ");
		$q->execute(array(
			':email' 	=> 	$_POST['email'],
		));
		// return array
		//$data = $q->fetchAll();
		$count = $q->rowCount();

		if($count != 0){
			$data = array('success' => 'true');
			echo json_encode($data);
		}else {
			$data = array('success' => 'false');
			echo json_encode($data);
		}
	}
}
?>